# -*- coding: utf-8 -*-
"""
Created on Tue Jun  5 21:16:41 2018

@author: sun haiyang
"""
import os
import glob
from nilearn.input_data import NiftiMasker
import pandas as pd
from scipy import stats
from ..plot import Boxplot
#%%
class Across_voxel_correlate(object):
    #作用原理：for instance:对30个subject PET_z CBF_z做cross voxel analysis，and store the result as excel and picture
    #参数说明：
    #参数说明：
    #返回值说明：
    #举例：
    #调用：
    #被调用：
    #bug：
    
    #below are necessary strings
    underline = '_'
    linkline = '-'
    os_sep = os.sep
    cmd_sep = ' && '
    space = ' '
    star = '*'
    condition = 'error'   #用于判断返回stdout_err的。
    suffix = '*.nii*'
    def __init__(self,input_list,column_name_list,item):
        print('in the Volume_spatial_correlate')
        print('input_list:',input_list)
        #test if the input_list has four parameters
        if len(input_list) != 4 :
            raise Exception("the number of elements of input_list is not equal to 4")
        self.initialize_parameters(input_list,column_name_list,item)
        self.spatial_correlate()
        
    def initialize_parameters(self,input_list,column_name_list,item):
        

        ##########################################################################重新整理传入参数
        self.group1_dirpath = input_list[0]
        self.group2_dirpath = input_list[1]
        self.mask_filepath = input_list[2]
        self.column_name_list = column_name_list
        self.tag = item
        print('os.sep:',self.os_sep)
        print('search_path:',self.group1_dirpath+self.os_sep+self.suffix) 
        print('search_path:',self.group2_dirpath+self.os_sep+self.suffix)
        self.group1_filepaths = glob.glob(self.group1_dirpath+self.os_sep+self.suffix)
        self.group2_filepaths = glob.glob(self.group2_dirpath+self.os_sep+self.suffix)
        self.group1_filepaths.sort()
        self.group2_filepaths.sort()
        print('group1_filepaths:',self.group1_filepaths)
        print('group2_filepaths:',self.group2_filepaths)
        if len(self.group1_filepaths) != len(self.group2_filepaths):
            raise Exception("the number of file of group1 is different from that of group2 ")
        self.fileamount = len(self.group1_filepaths)
        self.group_correlation = pd.DataFrame(columns=self.column_name_list)
        
    def spatial_correlate(self):
        groupmask = NiftiMasker(mask_img=self.mask_filepath)
        print('in saptial_correlate')
        for i in range(0,self.fileamount):
            print('iiiiiiiiiiiiiiii:',i)
            print('self.group1_filepaths[i]:',self.group1_filepaths[i])
            print('self.group2_filepaths[i]:',self.group2_filepaths[i])
            group1file_masked = groupmask.fit_transform(self.group1_filepaths[i])
            group2file_masked = groupmask.fit_transform(self.group2_filepaths[i])
            medi = stats.pearsonr(group1file_masked.flatten(),group2file_masked.flatten())
            medi = list(medi)
            medi.append(self.tag)
            print('medi:',medi)
            print('type_of_medi:',type(medi))
            print('medi_after_append:',medi)
            self.group_correlation = self.group_correlation.append(dict(zip(self.column_name_list,medi)),ignore_index=True)
            print('self.group_correlation:\n',self.group_correlation)

#%%
class Multi_across_voxel_correlate(object):
    #作用原理：do all kinds of permutation and  use a for-loop to pass them to Volume_spatial_correlate  
    #参数说明：
    #参数说明：
    #返回值说明：
    #举例：
    #调用：
    #被调用：
    #bug：
    def __init__(self,input_list):
        #get the input_list
        if len(input_list) != 2 :
            raise Exception("the number of elements of input_list is not equal to 2")
        grouppath_dict = input_list[0]
        column_name_list = input_list[1]
        coeff_pvalue_df = pd.DataFrame(columns=column_name_list)
        #the other parameters
        x = 2
        y = 0
        special_str = r'across_voxel_correlate'
        excel_suffix = '.xlsx' 
        graph_suffix = '.png'
        coeff_pvalue_file_str = os.sep + special_str + excel_suffix
        ms_file_str = os.sep + 'mms_' + special_str + excel_suffix   #ms表示mean  std
        graph_filename = special_str + graph_suffix
        
        #begin to caculate
        for item in grouppath_dict.keys():
            print('item:',item)
            print('grouppath_dict[item]:',grouppath_dict[item])
            output_dirpath = grouppath_dict[item][3]
            outcome = Across_voxel_correlate(grouppath_dict[item],column_name_list,item)
            coeff_pvalue_df = coeff_pvalue_df.append(outcome.group_correlation,ignore_index=True)
        print('coeff_pvalue_df:',coeff_pvalue_df)
        
        #将coeff_pvalue_df存到一个csv文件里
        coeff_pvalue_df.to_excel(output_dirpath+coeff_pvalue_file_str)
        #求mean std,放在一个DataFrame中，进而存到一个csv文件中
        medi = coeff_pvalue_df.groupby(column_name_list[x]).agg(['mean','median','std'])
        medi.to_excel(output_dirpath+ms_file_str,sheet_name='sheet1')
        
        #plot
        Boxplot(coeff_pvalue_df,column_name_list,x,y,output_dirpath,graph_filename)


#%%   a using example for Multi_volume_spatial_correlate
# the code below is the result filepath of kinds of modality
#zpet_dirpath = r'/media/root/Elements3/XuanWu_z_sm666_pearson_0609/PET_processing/PET_normalised_resliced_smoothed_Zstandardized'
#zcbf_dirpath = r'/media/root/Elements3/XuanWu_z_sm666_pearson_0609/CBF_processing/CBF_clear_background_SN_SR_SSM-6_z'
#zfalff_dirpath = r'/media/root/Elements3/XuanWu_z_sm666_pearson_0609/BOLD_processing/fALFF_z'
#zalff_dirpath = r'/media/root/Elements3/XuanWu_z_sm666_pearson_0609/BOLD_processing/ALFF_Z'
#zreho_dirpath = r'/media/root/Elements3/XuanWu_z_sm666_pearson_0609/BOLD_processing/ReHo_z'
##the code below is the groupmask filepath of kinds of modality
#cbf_groupmask_filepath = r'/media/root/Elements3/XuanWu_z_sm666_pearson_0609/CBF_processing/make_mask_before_z_standardize/sws_CBF_26_intersect_mask.nii'
#bold_groupmask_filepath = r''
#pet_groupmask_filepath = r''
#mni_brainmask_filepath = r'/media/root/Elements3/XuanWu_z_sm666_pearson_0609/CBF_processing/make_mask_before_z_standardize/BrainMask.nii'
#multi_modalitymask_filepath = r''
#output_dirpath = r'/media/root/Elements3/XuanWu_z_sm666_pearson_0609'
##the code below is the used as the excel title.
#column_name_list = ['coeff','pvalue','modalities']
#
#
#grouppath_dict = {'PET/CBF':[zpet_dirpath,zcbf_dirpath,cbf_groupmask_filepath],\
#                 'PET/fALFF':[zpet_dirpath,zfalff_dirpath,mni_brainmask_filepath],\
#                 'PET/ALFF':[zpet_dirpath,zalff_dirpath,mni_brainmask_filepath],\
#                 'PET/ReHo':[zpet_dirpath,zreho_dirpath,mni_brainmask_filepath],\
#                 'CBF/fALFF':[zcbf_dirpath,zfalff_dirpath,cbf_groupmask_filepath],\
#                 'CBF/ALFF':[zcbf_dirpath,zalff_dirpath,cbf_groupmask_filepath],\
#                 'CBF/ReHo':[zcbf_dirpath,zreho_dirpath,cbf_groupmask_filepath] }
#
#Multi_volume_spatial_correlate([grouppath_dict,column_name_list])